import Seo from '@/core/components/Seo'
import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner'
import { getIdFromSlug } from '@/core/utils/slug'
import productApi from '@/lib/product/api/productApi'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'

const BasicLayout = dynamic(() => import('@/core/components/layouts/BasicLayout'))
const Product = dynamic(() => import('@/lib/product/components/Product/Product'))

export default function ProductDetail() {
  const router = useRouter()
  const [product, setProduct] = useState(null)

  useEffect(() => {
    const { slug } = router.query

    const loadProduct = async () => {
      let product = await productApi({ id: getIdFromSlug(slug) })
      if (product?.length == 1) {
        product = product[0]
        const regexHtmlTags = /(<([^>]+)>)/gi
        const regexHtmlTagsExceptP = /<\/?(?!p\b)[^>]*>/g
        if (product.description.replace(regexHtmlTags, ' ').trim() == '') {
          product.description = ''
        }
        product.description = product.description.replace(regexHtmlTagsExceptP, ' ')
        product.description = product.description.trim()
      }
      setProduct(product)
    }
    if (slug) loadProduct()
  }, [router])

  return (
    <BasicLayout>
      <Seo
        title={product?.name || '' + ' - Indoteknik.com' || ''}
        description='Temukan pilihan produk B2B Industri &amp; Alat Teknik untuk Perusahaan, UMKM &amp; Pemerintah dengan lengkap, mudah dan transparan.'
        openGraph={{
          url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath,
          image: product?.image,
          type: 'product'
        }}
        additionalMetaTags={[
          {
            name: 'keywords',
            content: `${product?.name}, Harga ${product?.name}, Beli ${product?.name}, Spesifikasi ${product?.name}`
          }
        ]}
      />
      {!product && (
        <div className="container mx-auto flex justify-center pt-10">
          <LogoSpinner width={36} height={36} />
        </div>
      )}
      {product && <Product product={product} />}
    </BasicLayout>
  )
}
